<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true" label-width="65px">
        <SearchFormGroup
          :data="searchParam"
          @change-search="handleSearchChange"
          @change-gage-equip-code="changeEquipCode"
        />
        <!-- <el-form-item label="检具名称">
          <el-select v-model="searchParam.gageEquipMarkCode" placeholder="请选择检具名称" clearable filterable>
            <el-option v-for="item in gageEquipList" :key="item.toolCode" :label="item.toolName"
              :value="item.toolCode" />
          </el-select>
        </el-form-item> -->
        <el-form-item label="过程能力类型" label-width="92px">
          <el-select
            v-model="searchParam.cpkDatatype"
            placeholder="请选择过程能力类型"
            clearable
          >
            <el-option
              v-for="item in useDictionary('CpkDatatype')"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="过程能力时间" label-width="92px">
          <el-date-picker
            v-model="searchParam.timestamp"
            type="date"
            placeholder="请选择过程能力时间"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="searchBtn">
            <i-ep-search />
            搜索
          </el-button>
          <el-button @click="resetBtn">
            <i-ep-refresh />
            重置
          </el-button>
          <!-- <el-button type="primary" link @click="collapsed = !collapsed">
            {{ collapsed ? "展开" : "收起" }}
            <i-ep-arrowUp v-if="!collapsed" class="ml-[3px]" />
            <i-ep-arrowDown v-else class="ml-[3px]" />
          </el-button> -->
        </el-form-item>
      </el-form>
    </div>

    <div style="height: calc(100vh - 250px)">
      <el-card
        shadow="never"
        class="table-container"
        style="height: 100%; overflow-y: auto"
      >
        <!-- <template #header>
          <el-button type="primary" @click="downloadPDF"
            ><i-ep-download />PDF导出</el-button
          >
        </template> -->
        <div style="width: 100%" class="my-[10px]">
          <!-- <div
          style="
            font-size: 20px;
            display: flex;
            justify-content: flex-start;
            margin-bottom: 14px;
          "
        >
          <div style="line-height: 30px">
            <span>Process Capability Analysis</span>
          </div>
        </div> -->
          <div style="position: relative" v-if="tableData.length > 0">
            <img
              src="@/assets/images/logo-icon3.png"
              width="60"
              style="position: absolute; right: 0px; top: -20px"
            />
            <div
              style="
                font-size: 20px;
                display: flex;
                justify-content: flex-start;
                margin-bottom: 8px;
                margin-top: -10px;
              "
            >
              <div style="line-height: 30px">
                <span>Process Capability Analysis</span>
              </div>
            </div>
          </div>
          <table
            border="1"
            cellpadding="4"
            cellspacing="0"
            align="center"
            style="
              width: 100%;
              border-collapse: collapse; /* 使边框合并为单一边框 */
            "
            v-if="tableData.length > 0"
            :style="{
              fontSize: '14px',
              lineHeight: '20px',
              color: '#606266',
            }"
          >
            <colgroup>
              <col width="170" />
              <col width="280" />
              <col width="170" />
              <col width="240" />
              <col width="170" />
              <col width="180" />
            </colgroup>
            <tbody>
              <tr style="border-bottom: 1px solid #606266">
                <td colspan="1">
                  <div>
                    <div>&nbsp;</div>
                    <div>Plant</div>
                  </div>
                </td>
                <td colspan="1">
                  <div>
                    <div>&nbsp;</div>
                    <div>AT-DC-PDAL</div>
                  </div>
                </td>
                <td colspan="1">
                  <div>
                    <div>&nbsp;</div>
                    <div>Calculation method</div>
                  </div>
                </td>
                <td colspan="1">
                  <div>
                    <div>&nbsp;</div>
                    <div>&nbsp;</div>
                  </div>
                </td>
                <td colspan="1">
                  <div>
                    <div>Date from</div>
                    <div>Date to</div>
                  </div>
                </td>
                <td colspan="1">
                  <div>
                    <div>{{ paginatedData[0].createTime }}</div>
                    <div>
                      {{ paginatedData[paginatedData.length - 1].createTime }}
                    </div>
                  </div>
                </td>
              </tr>
              <tr style="border-bottom: 1px solid #606266">
                <td colspan="1">
                  <div>
                    <div>Production Line</div>
                    <!-- <div>Cost centre</div> -->
                  </div>
                </td>
                <td colspan="1">
                  <div>
                    <div>{{ searchParam.equipCode }}</div>
                    <!-- <div>&nbsp;</div> -->
                  </div>
                </td>
                <td colspan="1">
                  <div>
                    <div>Customer Name</div>
                  </div>
                </td>
                <td colspan="1">
                  <div>
                    <div>{{ searchParam.projectName }}</div>
                  </div>
                </td>
                <td colspan="1">
                  <div>
                    <div>Responsible Persion</div>
                  </div>
                </td>
                <td colspan="1">
                  <div>
                    <div>{{ userName }}</div>
                  </div>
                </td>
              </tr>
              <tr style="border-bottom: 1px solid #606266">
                <td colspan="1">
                  <div>
                    <div>Machine Number</div>
                    <div>Mach.Descr.</div>
                  </div>
                </td>
                <td colspan="1">
                  <div>
                    <div>{{ searchParam.gageEquipCode }}</div>
                    <div>{{ searchParam.gageEquipName }}</div>
                  </div>
                </td>
                <td colspan="1">
                  <div>
                    <div>Part number</div>
                    <div>Part description</div>
                  </div>
                </td>
                <td colspan="1">
                  <div>
                    <div>{{ searchParam.productCode }}</div>
                    <div>{{ searchParam.productName }}</div>
                  </div>
                </td>
                <!-- <td colspan="1">
                  <div>
                    <div>Work Cycle / Operatio</div>
                    <div>Inspector name</div>
                  </div>
                </td>
                <td colspan="1">
                  <div>
                    <div>9</div>
                    <div>{{ userName }}</div>
                  </div>
                </td> -->
              </tr>
              <tr style="border-bottom: 1px solid #606266">
                <td colspan="1">
                  <div>
                    <div>Comment</div>
                  </div>
                </td>
                <td colspan="5">
                  <div>
                    <div>&nbsp;</div>
                  </div>
                </td>
              </tr>
              <tr style="border-bottom: 1px solid #606266">
                <td colspan="1">
                  <div>
                    <div>Part no.</div>
                  </div>
                </td>
                <td colspan="2">
                  <div>
                    <div>{{ searchParam.productCode }}</div>
                  </div>
                </td>
                <td colspan="1">
                  <div>
                    <div>Part descr.</div>
                  </div>
                </td>
                <td colspan="2">
                  <div>
                    <div>{{ searchParam.productName }}</div>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        <el-table
          ref="dataTableRef"
          v-loading="loading"
          :data="paginatedData"
          highlight-current-row
          border
          @selection-change="handleSelectionChange"
          :header-cell-style="{ textAlign: 'center' }"
        >
          <el-table-column
            label="Chart.No"
            type="index"
            width="78"
            align="center"
          >
            <template #default="scope">
              {{ (currentPage - 1) * pageSize + scope.$index + 1 }}</template
            >
          </el-table-column>
          <el-table-column
            label="Char.Descr."
            prop="parmName"
            min-width="150"
            align="left"
            show-overflow-tooltip
          >
            <template #default="scope">
              <div
                style="
                  color: blue;
                  cursor: pointer;
                  text-decoration: underline;
                  word-break: break-all;
                "
                @click="showDetail(scope.row, scope.$index)"
              >
                {{ scope.row.parmName }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="ntot"
            min-width="70"
            align="right"
            show-overflow-tooltip
          >
            <template #header>
              <div class="flex justify-center relative">
                <span
                  style="
                    font-size: 16px;
                    position: relative;
                    display: inline-block;
                  "
                >
                  n
                  <span
                    style="
                      font-size: 11px;
                      position: absolute;
                      bottom: -6px;
                      left: 8px;
                      width: 20px;
                    "
                    >tot</span
                  >
                </span>
              </div>
            </template>
            <template #default="scope"> {{ scope.row.points.length }}</template>
          </el-table-column>
          <el-table-column
            prop="n<LSL>"
            min-width="80"
            align="right"
            show-overflow-tooltip
          >
            <template #header>
              <div class="flex justify-center relative">
                <span
                  style="
                    font-size: 16px;
                    position: relative;
                    display: inline-block;
                  "
                >
                  n
                  <span
                    style="
                      font-size: 11px;
                      position: absolute;
                      bottom: -6px;
                      left: 2px;
                      width: 50px;
                    "
                    >{{ "<LSL" }}</span
                  >
                </span>
              </div>
            </template>

            <template #default="scope"> {{ minToatal(scope.row) }}</template>
          </el-table-column>
          <el-table-column
            label="n>USL"
            prop="n>USL"
            min-width="80"
            align="right"
            show-overflow-tooltip
          >
            <template #header>
              <div class="flex justify-center relative">
                <!-- 父容器添加 position: relative -->
                <span
                  style="
                    font-size: 16px;
                    position: relative;
                    display: inline-block;
                  "
                >
                  n
                  <span
                    style="
                      font-size: 11px;
                      position: absolute;
                      bottom: -6px;
                      left: 2px;
                      width: 50px;
                    "
                    >{{ ">USL" }}</span
                  >
                </span>
              </div>
            </template>
            <template #default="scope"> {{ maxToatal(scope.row) }}</template>
          </el-table-column>
          <el-table-column
            label="X̅"
            prop="x"
            min-width="80"
            align="right"
            show-overflow-tooltip
          >
            <template #default="scope">
              {{ calculateAverage(scope.row.points).toFixed(5) }}</template
            >
          </el-table-column>
          <el-table-column
            label="S"
            prop="S"
            min-width="80"
            align="right"
            show-overflow-tooltip
          >
            <template #default="scope">
              {{ Number(scope.row.sampleStdDev).toFixed(4) }}</template
            >
          </el-table-column>
          <el-table-column
            label="index"
            prop="cp"
            min-width="100"
            align="center"
            show-overflow-tooltip
          >
            <template #default="scope">
              <div class="flex justify-evenly">
                <div>Cp</div>
                <div>{{ Number(scope.row.cp).toFixed(5) }}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="index"
            prop="cpk"
            min-width="100"
            align="center"
            show-overflow-tooltip
          >
            <template #default="scope">
              <div class="flex justify-evenly">
                <div>{{ scope.row.cpkType == "1" ? "cpk" : "ppk" }}</div>
                <div>{{ Number(scope.row.cpk).toFixed(6) }}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="index"
            prop="过程能力类型"
            min-width="100"
            align="center"
            show-overflow-tooltip
          >
            <template #default="scope">
              <div class="flex justify-evenly">
                <div>
                  {{ useDictionary("CpkDatatype", scope.row.cpkDatatype) }}
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="Overall ev"
            prop="ev"
            min-width="100"
            align="center"
            show-overflow-tooltip
          >
            <template #default="scope">
              <div>
                <svg-icon
                  v-if="faceRules(scope.row) == 'face1'"
                  icon-class="face1"
                  :size="'25'"
                  :color="'#7efa00'"
                />
                <!-- Big(scope.row.cpk).times(1.5) -->
                <svg-icon
                  v-if="faceRules(scope.row) == 'face2'"
                  icon-class="face4"
                  :size="'23'"
                  :color="'yellow'"
                />
                <svg-icon
                  v-if="faceRules(scope.row) == 'face3'"
                  icon-class="face3"
                  :size="'23'"
                  :color="'red'"
                />
              </div>
              <!-- <div>
              <svg-icon icon-class="face1" />
              <svg-icon icon-class="face2" />
              <svg-icon icon-class="face3" />
            </div> -->
            </template>
          </el-table-column>
          <el-table-column
            label="Value chart Individuals"
            prop="ev"
            min-width="250"
            align="center"
            show-overflow-tooltip
          >
            <template #default="scope">
              <div style="height: 100%">
                <reportPointLineChartNew
                  :key="Math.random().toString()"
                  :id="Math.random().toString()"
                  :showName="true"
                  :seriesData="scope.row"
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="Histogram Individuals"
            prop="ev"
            min-width="250"
            align="center"
            show-overflow-tooltip
          >
            <template #default="scope">
              <div style="height: 100%">
                <reportPointBarLineChart
                  :key="Math.random().toString()"
                  :id="Math.random().toString()"
                  ref="reportPointBarLineChart"
                  :showName="true"
                  :seriesData="calculateHistogram(scope.row.points)"
                />
              </div>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          :background="true"
          :current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          :page-sizes="[10, 25, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          class="mt-[20px]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />

        <!-- :style="{ height:pdfContentShow?'auto':'0px' }" -->
        <!-- v-if="pdfContentShow" -->
        <div
          v-if="pdfContentShow"
          id="printBox"
          class="tables-container"
          ref="pdfContent"
          style="overflow: hidden; position: relative; width: 750px"
        >
          <img
            src="@/assets/images/logo-icon3.png"
            width="50"
            style="position: absolute; right: 0px; top: -3px"
          />
          <div
            style="
              font-size: 20px;
              display: flex;
              justify-content: flex-start;
              margin-bottom: 8px;
            "
          >
            <div style="line-height: 30px">
              <span>Process Capability Analysis</span>
            </div>
          </div>
          <table
            border="1"
            cellpadding="4"
            cellspacing="0"
            align="center"
            style="width: 100%; border-collapse: collapse"
            v-if="tableData.length > 0"
            :style="{
              fontSize: '12px',
              lineHeight: '14px',
              color: '#000000',
            }"
          >
            <colgroup>
              <col width="170" />
              <col width="260" />
              <col width="170" />
              <col width="240" />
              <col width="150" />
              <col width="220" />
            </colgroup>
            <tbody>
              <tr style="border-bottom: 1px solid #606266">
                <td colspan="1">
                  <div>
                    <div>&nbsp;</div>
                    <div>Plant</div>
                  </div>
                </td>
                <td colspan="1">
                  <div>
                    <div>&nbsp;</div>
                    <div>AT-DC-PDAL</div>
                  </div>
                </td>
                <td colspan="1">
                  <div>
                    <div>&nbsp;</div>
                    <div>Calculation method</div>
                  </div>
                </td>
                <td colspan="1">
                  <div>
                    <div>&nbsp;</div>
                    <div>&nbsp;</div>
                  </div>
                </td>
                <td colspan="1">
                  <div>
                    <div>Date from</div>
                    <div>Date to</div>
                  </div>
                </td>
                <td colspan="1">
                  <div>
                    <div>{{ paginatedData[0].createTime }}</div>
                    <div>
                      {{ paginatedData[paginatedData.length - 1].createTime }}
                    </div>
                  </div>
                </td>
              </tr>
              <tr style="border-bottom: 1px solid #606266">
                <td colspan="1">
                  <div>
                    <div>Production Line</div>
                    <!-- <div>Cost centre</div> -->
                  </div>
                </td>
                <td colspan="1">
                  <div>{{ searchParam.equipCode }}</div>
                  <!-- <div>&nbsp;</div> -->
                </td>
                <td colspan="1">
                  <div>
                    <div>Customer Name</div>
                  </div>
                </td>
                <td colspan="1">
                  <div>
                    <div>{{ searchParam.projectName }}</div>
                  </div>
                </td>
                <td colspan="1">
                  <div>
                    <div>Responsible Persion</div>
                  </div>
                </td>
                <td colspan="1">
                  <div>
                    <div>{{ userName }}</div>
                  </div>
                </td>
              </tr>
              <tr style="border-bottom: 1px solid #606266">
                <td colspan="1">
                  <div>
                    <div>Machine Number</div>
                    <div>Mach.Descr.</div>
                  </div>
                </td>
                <td colspan="1">
                  <div>
                    <div>{{ searchParam.gageEquipCode }}</div>
                    <div>{{ searchParam.gageEquipName }}</div>
                  </div>
                </td>
                <td colspan="1">
                  <div>
                    <div>Part number</div>
                    <div>Part description</div>
                  </div>
                </td>
                <td colspan="1">
                  <div>
                    <div>{{ searchParam.productCode }}</div>
                    <div>{{ searchParam.productName }}</div>
                  </div>
                </td>
                <!-- <td colspan="1">
                  <div>
                    <div>Work Cycle / Operatio</div>
                    <div>Inspector name</div>
                  </div>
                </td>
                <td colspan="1">
                  <div>
                    <div>9</div>
                    <div>{{ userName }}</div>
                  </div>
                </td> -->
              </tr>

              <tr style="border-bottom: 1px solid #606266">
                <td colspan="1">
                  <div>
                    <div>Comment</div>
                  </div>
                </td>
                <td colspan="5">
                  <div>
                    <div>&nbsp;</div>
                  </div>
                </td>
              </tr>
              <tr style="border-bottom: 1px solid #606266">
                <td colspan="1">
                  <div>
                    <div>Part no.</div>
                  </div>
                </td>
                <td colspan="2">
                  <div>
                    <div>{{ searchParam.productCode }}</div>
                  </div>
                </td>
                <td colspan="1">
                  <div>
                    <div>Part descr.</div>
                  </div>
                </td>
                <td colspan="2">
                  <div>
                    <div>{{ searchParam.productName }}</div>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
          <div
            v-for="(group, index) in groupedData"
            :key="index"
            class="table-group"
          >
            <el-table
              ref="dataTableRef"
              class="print_table"
              size="small"
              v-loading="loading"
              :data="group"
              highlight-current-row
              border
              @selection-change="handleSelectionChange"
              :header-cell-style="{
                textAlign: 'center',
                fontSize: '12px',
                color: '#000',
              }"
              :row-style="{
                height: '39.5px',
                padding: '0px',
                margin: '0px',
              }"
              :cell-style="{
                height: '39.5px',
                padding: '0px !important',
                lineHeight: '12px',
                fontSize: '12px',
                color: '#000',
                textAlign: 'center',
                verticalAlign: 'middle',
                margin: '0px',
              }"
            >
              <el-table-column
                label="Chart.No"
                type="index"
                width="40"
                align="center"
              >
                <template #default="scope">
                  {{
                    index > 0
                      ? firstPageSize +
                        (index - 1) * otherPageSize +
                        scope.$index +
                        1
                      : scope.$index + 1
                  }}</template
                >
              </el-table-column>
              <el-table-column
                label="Char.Descr."
                prop="parmName"
                min-width="100"
                align="left"
              />
              <el-table-column prop="ntot" min-width="35" align="right">
                <template #header>
                  <div class="flex relative">
                    <span
                      style="
                        font-size: 12px;
                        position: relative;
                        display: inline-block;
                      "
                    >
                      n
                      <span
                        style="
                          font-size: 10px;
                          position: absolute;
                          bottom: -2px;
                          left: 8px;
                          width: 20px;
                          line-height: 10px;
                        "
                        >tot</span
                      >
                    </span>
                  </div>
                </template>
                <template #default="scope">
                  {{ scope.row.points.length }}</template
                >
              </el-table-column>
              <el-table-column prop="n<LSL" min-width="40" align="right">
                <template #header>
                  <div class="flex relative">
                    <span
                      style="
                        font-size: 12px;
                        position: relative;
                        display: inline-block;
                      "
                    >
                      n
                      <span
                        style="
                          font-size: 9px;
                          position: absolute;
                          bottom: -2px;
                          left: 1px;
                          width: 20px;
                          line-height: 10px;
                          width: 40px;
                        "
                        >{{ "<LSL" }}</span
                      >
                    </span>
                  </div>
                </template>

                <template #default="scope">
                  {{ minToatal(scope.row) }}</template
                >
              </el-table-column>
              <el-table-column
                label="n>USL"
                prop="n>USL"
                min-width="40"
                align="right"
              >
                <template #header>
                  <div class="flex relative justify-start">
                    <span
                      style="
                        font-size: 12px;
                        position: relative;
                        display: inline-block;
                      "
                    >
                      n
                      <span
                        style="
                          font-size: 9px;
                          position: absolute;
                          bottom: -2px;
                          left: 1px;
                          width: 20px;
                          line-height: 10px;
                          width: 40px;
                        "
                        >{{ ">USL" }}</span
                      >
                    </span>
                  </div>
                </template>
                <template #default="scope">
                  {{ maxToatal(scope.row) }}</template
                >
              </el-table-column>
              <el-table-column label="X̅" prop="x" min-width="60" align="right">
                <template #default="scope">
                  {{ calculateAverage(scope.row.points).toFixed(5) }}</template
                >
              </el-table-column>
              <el-table-column
                label="S"
                prop="sampleStdDev"
                min-width="50"
                align="right"
              >
                <template #default="scope">
                  {{ Number(scope.row.sampleStdDev).toFixed(4) }}
                </template>
              </el-table-column>
              <el-table-column
                label="index"
                prop="cp"
                min-width="75"
                align="center"
              >
                <template #default="scope">
                  <div class="flex justify-evenly">
                    <div>Cp</div>
                    <div>{{ Number(scope.row.cp).toFixed(5) }}</div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                label="index"
                prop="cpk"
                min-width="85"
                align="center"
              >
                <template #default="scope">
                  <div class="flex justify-evenly">
                    <div>{{ scope.row.cpkType == "1" ? "cpk" : "ppk" }}</div>
                    <div>{{ Number(scope.row.cpk).toFixed(6) }}</div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                label="Overall ev"
                prop="ev"
                min-width="50"
                align="center"
              >
                <template #default="scope">
                  <div>
                    <svg-icon
                      v-if="faceRules(scope.row) == 'face1'"
                      icon-class="face1"
                      :size="'25'"
                      :color="'#7efa00'"
                    />
                    <!-- Big(scope.row.cpk).times(1.5) -->
                    <svg-icon
                      v-if="faceRules(scope.row) == 'face2'"
                      icon-class="face4"
                      :size="'23'"
                      :color="'yellow'"
                    />
                    <svg-icon
                      v-if="faceRules(scope.row) == 'face3'"
                      icon-class="face3"
                      :size="'23'"
                      :color="'red'"
                    />
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="" prop="ev" align="center">
                <template #header>
                  <div class="flex relative justify-center">
                    <span
                      style="
                        font-size: 12px;
                        position: relative;
                        display: inline-block;
                        text-align: center;
                      "
                    >
                      Value chart<br />Individuals
                    </span>
                  </div>
                </template>
                <template #default="scope">
                  <div style="height: 100%">
                    <!-- <div style="height: 50px;"></div> -->
                    <!-- <img src="@/assets/images/logo-icon3.png" width="40" height="40"/> -->
                    <reportPointLineChartNew
                      :key="Math.random().toString()"
                      :id="Math.random().toString()"
                      :isPdf="true"
                      :showName="true"
                      :seriesData="scope.row"
                    />
                    <!-- <img
                    v-if="pcmPointLineChartRef?.imgLabel"
                    :src="pcmPointLineChartRef?.imgLabel"
                    width="730"
                  /> -->
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="" prop="ev" align="center">
                <template #header>
                  <div class="flex relative justify-center">
                    <span
                      style="
                        font-size: 12px;
                        position: relative;
                        display: inline-block;
                        text-align: center;
                      "
                    >
                      Histogram<br />Individuals
                    </span>
                  </div>
                </template>
                <template #default="scope">
                  <div style="height: 100%">
                    <!-- <div style="height: 50px;"></div> -->
                    <!-- <img src="@/assets/images/logo-icon3.png" width="40" height="40"/> -->
                    <reportPointBarLineChart
                      :key="Math.random().toString()"
                      :id="Math.random().toString()"
                      :isPdf="true"
                      :showName="true"
                      :seriesData="calculateHistogram(scope.row.points)"
                    />
                  </div>
                </template>
              </el-table-column>
            </el-table>
            <div class="avoid-page-break"></div>
          </div>
        </div>
      </el-card>
      <div class="absolute pl-[25px] bottom-[35px] left-[10px] w-[100%]">
        <el-button type="primary" @click="downloadPDF"
          ><i-ep-download />PDF导出</el-button
        >
      </div>
    </div>

    <pcmmeasurefeatures-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id: string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />

    <pcmConfigMeasurementsEdit
      :visible="configMeasurementDialog.visible"
      :title="configMeasurementDialog.title"
      :data="configMeasurementDialog.data"
      :abilityType="configMeasurementDialog.abilityType"
      @reset-table="(id: string) => (id?.length ? getTableList() : reset())"
      :is-readonly="configMeasurementDialog.readvisible"
      @change-visible="changeConfigMeasurementDialogVisible"
    />

    <el-dialog
      v-model="pdfPreviewDialog"
      title="PDF 预览"
      width="1100"
      :close-on-click-modal="false"
      draggable
      alignCenter
      class="printDialog"
    >
      <div style="height: 650px">
        <div v-if="pdfPreviewUrl" style="height: 650px">
          <embed
            :src="pdfPreviewUrl"
            type="application/pdf"
            style="width: 100%; height: 100%"
          />
        </div>
        <div v-else>正在生成预览，请稍候...</div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { useDictionary, useTable } from "@/utils/useTable";
import request from "@/utils/request";
import Big from "big.js";
import { getUserInfo } from "@/api/user/index";
import SearchFormGroup from "@/views/pcm/pcmMonitoring/components/SearchFormGroup1.vue";
import {
  getMdminspectiontoolApi,
  getMdmProcessEquipApi,
  getMdmProcessProjectApi,
  getMdmproductinfosApi,
  getMdmprojectinfosApi,
  getSpecificListApi,
  getMdmprocessListApi,
  getMdmProcessEquipApi1,
} from "@/utils/commonData";
import pcmConfigMeasurementsEdit from "@/views/pcm/pcmconfigmeasurements/components/pcmconfigmeasurements-edit.vue";
import html2pdfs from "html2pdf.js";
import { ElLoading } from "element-plus";
import { useRoute, useRouter } from "vue-router";

const route = useRoute();
const router = useRouter();

defineOptions({
  name: "PCMPROCESSCAPABILITYREPORT",
  inheritAttrs: false,
});

// 定义第一个表格的条目数和其他表格的条目数
const firstPageSize = 20;
const otherPageSize = 25;

// 计算属性：将数据按规则切分为多个数组
const groupedData = computed(() => {
  const result = [];

  if (tableData.value.length === 0) return result;

  // 第一个表格
  result.push(tableData.value.slice(0, firstPageSize));

  // 剩下的数据按每 20 条分组
  for (let i = firstPageSize; i < tableData.value.length; i += otherPageSize) {
    result.push(tableData.value.slice(i, i + otherPageSize));
  }

  return result;
});

// 请求参数
const requestApi = "/dmpDosPcm/pcmtimingpoint/cpkPage";

// 是否需要分页
const pagination = false;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  // 工段
  workshopSectionId: "",
  workshopSectionCode: "",
  // 项目
  // projectCode: "",
  // projectId: "",
  // 工序
  processCode: "",
  processId: "",
  // 设备
  equipCode: "",
  equipId: "",
  // 产品型号
  productCode: "",
  productId: "",
  // 检具类型
  gageEquipToolKind: "",
  // 检具名称
  gageEquipCode: "",
  // 机器号
  gageEquipMarkCode: "",
  cpkDatatype: "",
  timestamp: "",
};

const deleteParam = {
  api: "/dmpDosPcm/pcmmeasurefeatures/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

const currentPage = ref(1); // 当前页码
const pageSize = ref(10); // 每页显示的条目数
const total = computed(() => tableData.value.length); // 总条目数

// 计算当前页的数据
const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return tableData.value.slice(start, end);
});

// 处理每页显示条目数的变化
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  currentPage.value = 1; // 重置到第一页
};

// 处理当前页码的变化
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
};

const pageable = reactive({
  total: 0,
  pageNum: 0,
  pageSize: 0,
});

// 表格操作 Hooks
const {
  tableData,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  //   handleSizeChange,
  //   handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

// --------------------------------------------------------------------------------------------------------组件 开始
// 处理传回数据
const handleSearchChange = (data) => {
  Object.assign(searchParam.value, data);
  // 可执行字段相关的特定逻辑
};
// 间距变化
const changeEquipCode = (id: string) => {
  if (id) {
  }
};
// --------------------------------------------------------------------------------------------------------组件 结束
const resetBtn = () => {
  Object.assign(searchParam.value, searchParamInit);
  tableData.value = [];
};

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

const configMeasurementDialog = reactive<
  DialogOption & { abilityType: string }
>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
  abilityType: "",
});

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

function changeConfigMeasurementDialogVisible(value: boolean) {
  configMeasurementDialog.visible = value;
  if (!value) {
    configMeasurementDialog.data = {};
  }
}

const userName = ref<string | undefined>("");
onMounted(async () => {
  // // 获取量检具列表
  getGageEquipList({});

  await getUserInfo().then(({ data }) => {
    userName.value = data.userName;
  });
});

// 获取量检具列表
const gageEquipList = ref<any>([]);

async function getGageEquipList(params) {
  gageEquipList.value = (await getMdminspectiontoolApi({})) || [];
}

const searchBtn = () => {
  search();
};

// 取最大值及最小值

function findMinMax(arr) {
  const min = Math.min(...arr);
  const max = Math.max(...arr);
  return { min, max };
}

function createRangeArray(start, end, segments) {
  const step = (end - start) / segments;
  return Array.from({ length: segments }, (_, i) => start + i * step);
}

// const result = createRangeArray(1, 2, 12);

const pcmPointBarLineChart = (data) => {
  const { min, max } = findMinMax(data.points);
  const result = createRangeArray(min, max, 14);
  let mm = {
    ydata1: [],
    ydata2: [],
    xdata: [],
  };

  let xx = 0;
  if (data.points.length < 50) {
    // 计算立方根（3√27）
    xx = Big(Math.pow(data.points.length, 1 / 2)).toFixed(0); // 结果: 3
  } else {
    xx = Big(Math.pow(data.points.length, 1 / 3))
      .times(2)
      .toFixed(0); // 结果: 3
  }

  let result1 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; // 初始化四个区间的计数器
  let result2 = new Array(Math.max(0, Math.floor(xx))).fill(0);

  const resultf = createRangeArray(min, max, xx);

  // 确保 points 是升序排列的
  const sortedPoints = [...result].sort((a, b) => a - b);

  // 遍历每个数据点
  for (const point of data.points) {
    for (let i = 0; i < 14; i++) {
      const start = sortedPoints[i];
      const end = sortedPoints[i + 1];

      // 判断点是否落在当前区间（左闭右开）
      if (point >= start && point <= end) {
        result1[i]++;
        break; // 找到匹配区间后跳出循环
      }
    }
  }

  // calculateHistogram(data.points, xx);
  mm.ydata1 = result1;
  mm.ydata2 = result1;
  mm.xdata = [];

  return mm;
  // return result
};

const calculateHistogram = (values) => {
  let bins = 0;
  if (values.length < 50) {
    // 计算立方根（3√27）
    bins = Big(Math.pow(values.length, 1 / 2)).toFixed(0); // 结果: 3
  } else {
    bins = Big(Math.pow(values.length, 1 / 3))
      .times(2)
      .toFixed(0); // 结果: 3
  }

  if (values.length === 0) return new Array(bins).fill(new Big(0));

  // 转换所有值为 Big 类型
  const bigValues = values.map((v) => new Big(v));

  // 计算最大最小值
  const min = bigValues.reduce((a, b) => (a.lt(b) ? a : b), bigValues[0]);
  const max = bigValues.reduce((a, b) => (a.gt(b) ? a : b), bigValues[0]);

  // 处理所有值相等的情况
  if (min.eq(max)) {
    const result = new Array(bins).fill(new Big(0));
    result[0] = new Big(values.length);
    return result;
  }

  // 计算区间宽度（使用 big.js 运算）
  const binWidth = max.minus(min).div(bins);

  // 初始化统计数组（使用 Big 类型）
  const histogram = Array.from({ length: bins }, () => new Big(0));

  // 遍历数据点
  bigValues.forEach((value) => {
    let binIndex = value.minus(min).div(binWidth).round(0, Big.roundDown);

    // 处理最大值边界
    if (value.eq(max)) {
      binIndex = bins - 1;
    } else {
      binIndex = binIndex.lt(0) ? 0 : binIndex.gte(bins) ? bins - 1 : binIndex;
    }

    histogram[binIndex] = histogram[binIndex].plus(1);
  });

  let mm = {
    ydata1: [],
    ydata2: [],
    xdata: [],
  };
  mm.ydata1 = histogram.map((v) => v * 1);
  mm.ydata2 = histogram.map((v) => v * 1);
  mm.xdata = [];

  return mm;
};

// // 定义数据源
// const points = ref([10, 20, 30, 40, 50]) // 五个点
// const dataPoints = ref([15, 25, 35, 45, 55]) // 待统计的点

// // 计算属性：统计每个区间内的点数
// const intervalsCount = computed(() => {
//   const result = [0, 0, 0, 0] // 初始化四个区间的计数器

//   // 确保 points 是升序排列的
//   const sortedPoints = [...points.value].sort((a, b) => a - b)

//   // 遍历每个数据点
//   for (const point of dataPoints.value) {
//     for (let i = 0; i < 4; i++) {
//       const start = sortedPoints[i]
//       const end = sortedPoints[i + 1]

//       // 判断点是否落在当前区间（左闭右开）
//       if (point >= start && point < end) {
//         result[i]++
//         break // 找到匹配区间后跳出循环
//       }
//     }
//   }

//   return result
// })

// 小于公差下限
const minToatal = (row) => {
  let count = row.points.filter((element) => element < row.ltl).length;
  return count;
};
// 大于公差上限
const maxToatal = (row) => {
  let count = row.points.filter((element) => element > row.utl).length;
  return count;
};
// 样本均值

function calculateAverage(arr) {
  if (arr.length === 0) return 0; // 避免除以0的错误
  const sum = arr.reduce(
    (accumulator, currentValue) => accumulator + Number(currentValue),
    0
  );
  return sum / arr.length;
}

const pdfContent = ref(null);
const pdfContentShow = ref(false);
const pdfPreviewDialog = ref(false);
const pdfPreviewUrl = ref<any>(null);

const exportPDF = () => {
  // 同上述代码
};

// const pcmPointLineChartRef = ref();

const pdfOptions = {
  filename: `Process Capability Analysis.pdf`, // 指定生成文件的名称
  margin: [5, 5],
  // image: { type: "png", quality: 2 },
  image: { type: "jpeg", quality: 1 },
  html2canvas: {
    scale: 2,
    useCORS: true,
    logging: false,
    letterRendering: true,
  },
  jsPDF: { unit: "mm", format: "a4", orientation: "portrait" },
  splitTextToRows: false, // 关闭文本拆分行
  pagebreak: { mode: ["css", "legacy"], after: ".avoid-page-break" }, // 自定义分页规则
};

const downloadPDF = () => {
  if (tableData.value.length === 0) {
    ElMessage.warning("数据不能为空，请先搜索");
    return;
  }
  const loading = ElLoading.service({
    lock: true,
    text: "正在为您生成PDF，请稍后...",
  });
  setTimeout(() => {
    pdfContentShow.value = true;
    setTimeout(() => {
      const element = document.querySelector(".tables-container");
      html2pdfs()
        .set(pdfOptions)
        .from(element)
        .save()
        .finally(() => {
          pdfContentShow.value = false;
          loading.close();
        });
    }, 500);
  }, 100);
};

//笑脸规则
const faceRules = (item) => {
  if (item.cpkType == "1") {
    if (Big(item.cpk) > Big(item.cpmLowData.cpkLow).times(1.1)) {
      return "face1";
    } else if (
      Big(item.cpk) > Big(item.cpmLowData.cpkLow) &&
      Big(item.cpk) < Big(item.cpmLowData.cpkLow).times(1.1)
    ) {
      return "face2";
    } else if (Big(item.cpk) < Big(item.cpmLowData.cpkLow)) {
      return "face3";
    }
  }
  if (item.cpkType == "2") {
    //  if(item.ppk>item.cpmLowData.ppkLow * 1.1){
    //     return 'face1'
    //   }else if(item.ppk>item.cpmLowData.ppkLow  &&item.cpk<item.cpmLowData.ppkLow * 1.1){
    //  return 'face2'
    //   }else if (item.ppk<item.cpmLowData.ppkLow){
    //     return 'face3'
    //   }
    if (Big(item.ppk) > Big(item.cpmLowData.ppkLow).times(1.1)) {
      return "face1";
    } else if (
      Big(item.ppk) > Big(item.cpmLowData.ppkLow) &&
      Big(item.ppk) < Big(item.cpmLowData.ppkLow).times(1.1)
    ) {
      return "face2";
    } else if (Big(item.ppk) < Big(item.cpmLowData.ppkLow)) {
      return "face3";
    }
  }

  // if (item.data > item.setValue * 1.1) {
  //     return '😊' // 绿色笑脸（超出设置值10%）
  //   } else if (item.currentValue > item.setValue) {
  //     return '😐' // 黄色扁嘴（超出设置值但不超过10%）
  //   } else {
  //     return '😢' // 红色哭脸（未超出设置值）
  //   }
};

watch(
  () => searchParam.value,
  (newVal) => {
    searchParam.value.gageEquipMarkCode = newVal.gageEquipCode;
  },
  {
    deep: true,
  }
);

// 点击进入 详情

const showDetail = (row, index) => {
  console.log(row, index);

  localStorage.setItem(
    "seacher",
    JSON.stringify({
      ...searchParam.value,
      type: searchParam.value.cpkDatatype,
      specificId: row.parmid,
      specificName: row.parmName,
      index: index + 1,
      value: row.cpk,
      count: 125,
      trendDataId: row.id,
    })
  );
  router.push({
    path: "/pcm/pcmmonitoringpoint",
  });
};
</script>
<style lang="scss" scoped>
.face_svg {
  font-size: 26px;
  position: absolute;
  right: 0;
  top: 8px;
}

:deep(.search-container .el-form--inline .el-form-item) {
  margin-right: 23px;
  width: 260px;
}

:deep(.print_table .cell) {
  padding: 0 2px !important;
  line-height: 13px !important;
  // height: 39.5px !important;
  // display: flex !important;
  // align-items: center !important;
  // justify-content: center !important;
}

:deep(.print_table .el-table td.el-table__cell div) {
  height: 39.5px;
}

:deep(tr) {
  page-break-inside: avoid;
}

.table-group {
  margin-top: 15px;
  // page-break-inside: avoid;
}

// * 设置 el-table 的每一行高度 */
:deep(.print_table .el-table__row) {
  height: 40px !important;
}
</style>
